package com.william.jdbcplus.core.condition.segment.impl;

import com.william.jdbcplus.core.enums.SqlKeyword;
import com.william.jdbcplus.core.toolkit.StringPool;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Having SQL 片段
 *
 * @author niliwei
 */
public class HavingSegmentList extends AbstractSegmentList {
    @Override
    public String getSegment() {
        if (isEmpty()) {
            return StringPool.EMPTY;
        }

        //获取合并 not 后的列表
        List<String> mergeNotList = new ArrayList<>();
        boolean lastMatchNot = false;
        for (int i = 0; i < this.size(); i++) {
            String current = this.get(i);
            boolean matchNot = current.equals(SqlKeyword.NOT.toString());
            if (matchNot) {
                lastMatchNot = true;
            } else {
                if (lastMatchNot) {
                    mergeNotList.add(SqlKeyword.NOT.toString() + StringPool.SPACE + current);
                } else {
                    mergeNotList.add(current);
                }

                lastMatchNot = false;
            }
        }

        // 获取 结果列表
        List<String> resultList = new ArrayList<>();
        // 上一次游标关键字，非 and or not 时为空
        String lastKeyWord = StringPool.EMPTY;
        for (int i = 0; i < mergeNotList.size(); i++) {
            // 当前项
            String current = mergeNotList.get(i);
            boolean matchAnd = current.equals(SqlKeyword.AND.toString());
            boolean matchOr = current.equals(SqlKeyword.OR.toString());
            //是关键字
            if (matchAnd || matchOr) {
                lastKeyWord = current;
            } else {
                if (i == 0) {
                    resultList.add(current);
                } else {
                    if (lastKeyWord.equals(StringPool.EMPTY)) {
                        if(resultList.size() == 0){
                            resultList.add(current);
                        } else {
                            resultList.add(SqlKeyword.AND.toString() + StringPool.SPACE + current);
                        }
                    } else {
                        if(resultList.size() == 0){
                            resultList.add(current);
                        } else{
                            resultList.add(lastKeyWord + StringPool.SPACE + current);
                        }
                    }
                }
                lastKeyWord = StringPool.EMPTY;
            }
        }

        return resultList.stream().collect(Collectors.joining(StringPool.SPACE));
    }

    @Override
    public String getSql() {
        if (isEmpty()) {
            return StringPool.EMPTY;
        }
        return StringPool.SPACE + SqlKeyword.HAVING.getSegment() + StringPool.SPACE + getSegment();
    }
}
